package com.game.Components;

import com.Math.Polygon2D;
import com.Math.Vector2D;
import com.pixels.Display;
import com.pixels.graphics.Drawer;
import com.pixels.input.Controller;
import java.util.ArrayList;

public class Ship extends Entity  {

	public int score = 0;
	public int life = 3;
	int MAX_BULLETS = 8;
	double BULLET_TIME = 60;
	int MAX_SPEED = 10;

	int numBullets = 0;

	double friction = 0.999;
	double thrust = 0.8;
	
	boolean alive = true;
	public ArrayList<Bullet> bullets;
	Bullet bullet;
	boolean drawFlame = false;

	public boolean visible = true;
	int timeinVisible = 0;

	public double radius = 10;
	private boolean shot = false;
	public Polygon2D flame;

	public Ship() {
		super(Display.WIDTH/2, Display.HEIGHT/2,0);
		//tegning av skipet
		Vector2D[] ship = { new Vector2D(100, 0), new Vector2D(110, 25), new Vector2D(100, 20), new Vector2D(90, 25), };
		polygon = new Polygon2D(ship);
		//tegning av flammen
		Vector2D[] flameD = { new Vector2D(100, 20), new Vector2D(104, 25), new Vector2D(100, 35), new Vector2D(96, 25), };
		flame = new Polygon2D(flameD, 100, 15);
		//flytter skipet til midten av skjermen
		polygon.moveTo(pos);
		rotateSpeed = Math.PI/12;
		bullets = new ArrayList<Bullet>();
	}

	public void tick(Controller controls) {

		speed.multiply(friction);

		if (controls.turnLeft) {
			polygon.rotateRad(-rotateSpeed);

			flame.rotateRad(-rotateSpeed);
		}
		if (controls.turnRight) {
			polygon.rotateRad(rotateSpeed);
			flame.rotateRad(rotateSpeed);
		}
		if (controls.forward) {
			if (speed.add2(polygon.verts[0].normalize2().multiply2(thrust)).length() < MAX_SPEED) {
				speed.add(polygon.verts[0].normalize2().multiply2(thrust));
			}
			drawFlame = true;
		} else {
			drawFlame = false;
		}

		pos.add(speed);

		if (controls.space && bullets.size() < MAX_BULLETS) {
			if (!shot) {
				shoot();
				shot = true;
			}
		} else {
			shot = false;
		}
		polygon.moveTo(pos);
		flame.center.setTo(polygon.center);
		boundaries();
		for (Bullet b : bullets) {
			b.move();
			if (b.ticksAlive > BULLET_TIME) {

				bullet = b;
			}
		}
		bullets.remove(bullet);

		if (visible == false) {
			timeinVisible++;
		}
		if (timeinVisible > 90 && visible == false) {
			visible = true;
			timeinVisible = 0;
		}
	}

	public void draw(Drawer draw) {

		if (visible == false) {
			draw.setColor(0x00ff00);
		} else {
			draw.setColor(0x0000ff);
		}
		draw.drawPoly(polygon);
		if (drawFlame) {
			draw.setColor(0xff0000);
			draw.drawPoly(flame);
		}

		for (Bullet b : bullets) {
			b.draw(draw);
		}
	}

	private void shoot() {
		bullets.add(new Bullet(pos, polygon.dir));
	}

	public void destroy() {
		pos.setTo(400, 300);
		speed.setToZero();
		life -= 1;
		if (life < 1) {
			pos.setToZero();
		}
		visible = false;
	}
}